<template>
	<view class="z-img-upload">
		<u-upload maxCount="1" uploadIcon="plus" :disabled="disabled" :fileList="fileList" :multiple="false" @afterRead="afterRead"
			@delete="deletePic"></u-upload>
		<u-notify ref="notify"></u-notify>
	</view>
</template>

<script>
	import {
		mapState
	} from 'vuex'
	import {
		API_BASE_URL
	} from '@/config.js'
	import NotifyMix from '@/mixins/notify-fix.js'
	import Util from '@/utils/index.js'
	import API from '@/api/index.js'
	export default {
		props: ['value', 'disabled', 'lon', 'lat', 'remark'],
		mixins: [NotifyMix],
		data() {
			return {
				fileList: [],
			}
		},
		computed: {
			...mapState({
				userInfo: state => state.user.userInfo,
				token: state => state.user.token
			})
		},
		methods: {
			async afterRead(fileData) {
				const that = this
				if (Util.StringUtil.isEmpty(that.lon) || Util.StringUtil.isEmpty(that.lat)) {
					that.notifyFail('请先获取经纬度')
					return false
				}
				if (fileData.file.type !== 'image') {
					that.notifyFail('仅允许上传图片格式文件')
					return false
				}
				let blob = fileData.file.file
				if (fileData.file.size / 1024 > 600) {
					blob = await Util.imageConversion.compressAccurately(fileData.file.file, 600)
				}
				uni.uploadFile({
					header: {
						'Authorization': 'Bearer ' + that.token,
						'Content-Type': 'multipart/form-data'
					},
					url: API_BASE_URL + "/cj_record/upload_image",
					filePath: fileData.file.url,
					name: 'file',
					formData: {
						longitude: that.lon,
						latitude: that.lat,
						realName: that.userInfo.realName,
						time: Util.dayjs().format("YYYY-MM-DD HH:mm:ss"),
						remark: that.remark
					},
					success(res) {
						res = JSON.parse(res.data)
						if (res.code !== 200 || !res.data) {
							that.notifyFail('上传失败')
							return
						}
						that.getUrl(res.data).then(res => {
							that.fileList.splice(0, that.fileList.length, {
								url: res
							})
						})
						
					},
					fail(err) {
						that.notifyFail('上传失败')
					}
				})
			},
			deletePic() {
				this.fileList.splice(0, this.fileList.length)
			},
			getPath (url) {
			  const index = url.indexOf('upload');
			  return index !== -1 ? url.slice(index) : "";
			},
			async getUrl (path) {
				const res = await API.CjRecordApi.previewImage({path})
				if (res.code !== 200 || !res.data) {
					that.notifyFail('获取图片预览地址失败')
					return 
				}
				return res.data
			}
		},
		mounted() {
			// 组件初始化，根据 value 转 fileList
			const that = this
			if (!Util.StringUtil.isEmpty(that.value)) {
				that.getUrl(that.value).then(res => {
					that.fileList.splice(0, that.fileList.length, {
						url: res
					})
				})
			}
		},
		watch: {
			// 根据 fileList 的变化更新 value 值
			fileList: {
				handler(n, o) {
					const that = this
					if (n.length === 0) {
						that.$emit('setVal', '')
					} else if (n.length > 0) {
						if (!Util.StringUtil.isEmpty(n[0].url)) {
							const path = that.getPath(n[0].url).split('?')[0]
							that.$emit('setVal', path)
						}
					}
				},
				deep: true
			}
		}
	}
</script>

<style>
	.z-img-upload {
		display: inline-block;
	}
</style>